package com.sy.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sy.dto.TokenUser;
import com.sy.entity.Admin;
import com.sy.entity.AdminRole;
import com.sy.entity.Role;
import com.sy.mapper.AdminMapper;
import com.sy.mapper.AdminRoleMapper;
import com.sy.mapper.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CacheDetailService implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private RoleMapper roleMapper;


    @Override
    //获取结果后对结果进行缓存
    //当用户信息发生变化时可以清除缓存
    //注意：如果是手动改变数据库数据，则这里无法监控到缓存需要更新，一般是程序代码中更新用户的同时刷新缓存
//    @Cacheable(cacheNames = AppConstant.AUTH_USER_REDIS_CACHE_PREFIX, key = "#userName")
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        log.info("从数据库中获取用户信息...");
        //获取用户信息
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username",userName);
        Admin admin = adminMapper.selectOne(wrapper);
        if (null == admin) {
            throw new UsernameNotFoundException("用户" + userName + "不存在");
        }
        //获取权限关系表数据
        QueryWrapper<AdminRole> queryWrapper = new QueryWrapper();
        queryWrapper.eq("aid",admin.getId());
        List<AdminRole> adminRoles = adminRoleMapper.selectList(queryWrapper);
        //获取角色信息
//        System.out.println(userRoles);
       // System.out.println(userRoles.stream().map(userRole -> userRole.getRoleId()).collect(Collectors.toList()));
        List<Role> roles = roleMapper.selectBatchIds(adminRoles.stream().map(adminRole -> adminRole.getRoleId()).collect(Collectors.toList()));
        List<? extends GrantedAuthority> authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.getRole())).collect(Collectors.toList());
        List<String> roleNames = roles.stream().map(role -> role.getRole()).collect(Collectors.toList());
        UserDetails userDetails = new TokenUser(admin.getId(), userName, admin.getPwd(), authorities, roleNames);
        return userDetails;
    }
}
